<!--精准匹配-->
<template>
    <view class="personFormStyle">
        <!-- 精准匹配 -->
        <view v-if="!isMatching" style=" padding: 30rpx;">
            <uni-forms :modelValue="individualForm" label-position="right" ref="individual" :labelWidth="80">
                <view>
                    <uni-forms-item name="enterpriseName">
                        <template slot="label">
                            <view class="labelStyle">
                                <text class="labelText">公司全称</text>
                                <text class="label-str">*</text>
                            </view>
                        </template>
                        <view class="companyName">
                            {{ individualForm.enterpriseName }}
                        </view>
                    </uni-forms-item>
                    <uni-forms-item ref="creditCode" name="creditCode">
                        <template slot="label">
                            <view class="labelStyle">
                                <text class="labelText">纳税人识别号</text>
                                <text class="label-str">*</text>
                            </view>
                        </template>
                        <view class="companyName">
                            {{ individualForm.creditCode }}
                        </view>
                    </uni-forms-item>
                    <uni-forms-item style="padding-bottom: 10rpx;" ref="province" name="province">
                        <template slot="label">
                            <view class="labelStyle">
                                <text class="labelText">所属省份</text>
                                <text class="label-str">*</text>
                            </view>
                        </template>
                        <picker @change="provinceChange" :value="provinceIndex" :range="provinceList">
                            <text :style="{ color: '#999', 'font-size': '34rpx' }"
                                style="padding-right: 10px; margin-top: 20rpx;">
                                {{
                                    individualForm.province
                                        ? individualForm.province
                                        : "请选择所属省份"
                                }}</text>
                        </picker>
                    </uni-forms-item>
                    <uni-forms-item ref="phone" name="phone" class="formItem">

                        <template slot="label">
                            <view class="labelStyle">
                                <image class="img" @click="showInfo('phone')" :src="require('../static/gantanha.png')">
                                </image>
                                <text class="labelText">电子税务局账号</text>
                                <text class="label-str">*</text>
                            </view>
                        </template>
                        <uni-easyinput v-model="individualForm.phone" @focus="heightLong = true"
                            @blur="heightLong = false" :clearable="false" :inputBorder="false"
                            placeholder="请输入税务账号"></uni-easyinput>
                    </uni-forms-item>
                    <uni-forms-item style="margin-top: 10rpx;" ref="creditPwd" name="creditPwd" class="formItem">
                        <template slot="label">
                            <view class="labelStyle">
                                <image class="img" @click="showInfo('creditPwd')"
                                    :src="require('../static/gantanha.png')"></image>
                                <text class="labelText">税务密码</text>
                                <text class="label-str">*</text>
                            </view>
                        </template>
                        <uni-easyinput v-model="individualForm.creditPwd" type="password" @focus="heightLong = true"
                            @blur="heightLong = false" :clearable="false" :inputBorder="false"
                            placeholder="请输入税务密码"></uni-easyinput>
                    </uni-forms-item>
                    <uni-forms-item v-if="needCode" name="smsCaptcha" ref="smsCaptcha">
                        <template slot="label">
                            <view class="labelStyle">
                                <text class="labelText">验证码</text>
                                <text class="label-str">*</text>
                            </view>
                        </template>
                        <uni-easyinput v-model="individualForm.smsCaptcha" maxlength="6" @focus="heightLong = true"
                            @blur="heightLong = false" :clearable="false" :inputBorder="false" placeholder="请输入验证码">
                            <template slot="right">
                                <button :class="!btnDisabled ? 'btnStyle' : 'btnDisabledStyle'" @click="getCode">
                                    {{ btnDisabled ? `${countDown}秒后重发` : code_QY }}
                                </button>
                            </template>
                        </uni-easyinput>
                    </uni-forms-item>
                </view>
            </uni-forms>
            <view class="footerBox">
                <view class="btnBox">
                    <button class="informationBtn" @click="individualConfirmFun">
                        下一步
                    </button>
                </view>
                <view class="checkBox">
                    <checkbox-group @change="isChecked = !isChecked" style="width: auto">
                        <checkbox color="#488AFD" style="transform: scale(0.7)" :checked="isChecked" shape="circle">
                        </checkbox>
                    </checkbox-group>
                    <view style="font-size: 24rpx; color: #999;">我已阅读并同意
                        <text style="color: #2872fd" @click="toAgreement">《授权协议》</text>
                    </view>
                </view>
            </view>
        </view>
        <uni-popup ref="popupSubmit" background-color="#fff">
            <view class="popup-content" style="text-align: center">
                <view class="title">{{
                    info[infoType] ? info[infoType].title : ""
                    }}</view>
                <view class="content" v-if="info[infoType]">
                    <view v-for="(item, idx) in info[infoType].conten" :key="idx">{{
                        item
                        }}</view>
                </view>
                <view class="btn-st" @click="closeDialog">我知道了</view>
                <view @click="closeDialog" style="
            width: 30rpx;
            height: 30rpx;
            position: absolute;
            right: 26rpx;
            top: 20rpx;
          ">
                </view>
            </view>
        </uni-popup>
        <Matching v-if="isMatching" />
        <loading :show="loading" />
    </view>
</template>
<script>
import {
    onlyAccountApi,
    sendSmsCodeApi,
    taxCaptchaApi,
    taxCompanyLoginApi,
    createMatchEnterpriseApi,
} from "@/api/product";
import { getProvince } from "@/api/public";
import { API_CHANNELTYPE } from "@/config/app";
import Matching from "../components/match.vue";

export default {
    components: {
        Matching
    },
    data() {
        return {
            tabIndex: 1,
            isMatching: false, //是否正在匹配
            stepIndex: 0,
            individualForm: {
                province: "",
                creditCode: "",
                creditPwd: "",
                enterpriseName: "",
                phone: "",
                smsCaptcha: "",
            },
            needCode: false, //验证是否需要验证码
            indiviRules: {
                province: {
                    rules: [{ required: true, errorMessage: "请选择企业所在省份" }],
                },
                creditCode: {
                    rules: [
                        {
                            required: true,
                            errorMessage: "请输入税务账号",
                        },
                        {
                            validateFunction: (rule, value, data, callback) => {
                                return new Promise((resolve, reject) => {
                                    if (!value) {
                                        reject(new Error("请输入税务账号"));
                                    } else {
                                        let pattern = /^[a-zA-Z0-9]+$/;
                                        if (pattern.test(value)) {
                                            resolve();
                                        } else {
                                            reject(new Error("请输入税务账号"));
                                        }
                                    }
                                });
                            },
                        },
                    ],
                },
                creditPwd: {
                    rules: [{ required: true, errorMessage: "请输入税务密码" }],
                },
                smsCaptcha: {
                    rules: [{ required: true, errorMessage: "请输入验证码" }],
                },
                phone: {
                    rules: [
                        { required: true, errorMessage: "请输入手机号" },
                        {
                            validateFunction: (rule, value, data, callback) => {
                                return new Promise((resolve, reject) => {
                                    if (!value) {
                                        reject(new Error("手机号不能为空"));
                                    } else {
                                        const reg = /^1[3-9][0-9]\d{8}$/;
                                        if (reg.test(value)) {
                                            resolve();
                                        } else {
                                            reject(new Error("请输入正确的手机号"));
                                        }
                                    }
                                });
                            },
                            errorMessage: "手机号码不正确",
                        },
                    ],
                },
                commpanyName: {},
            },
            enterpriseId: null,
            uuid: null,
            taskId: null,

            notNeedCode: ["tianjin", "zhejiang", "hubei", "guangdong"],
            isChecked: false,
            code_QY: "获取验证码",
            loading: false,
            disabled: false,
            heightLong: false,
            btnDisabled: false,
            clickCode: false,
            countDown: 60, //按钮倒计时
            provinceIndex: 0,
            provinceList: [],
            provinceListObj: [],
            provinceObj: null, //选择的省份数据

            info: {
                phone: {
                    title: "税务账号",
                    conten: [
                        "1、该账号是您公司的国税账号;",
                        "2、可以询问公司的财务或办税员;",
                        "3、部分地区授权登录会有验证码，将会发送您公司绑定国税账号手机上",
                    ],
                },
                creditPwd: {
                    title: "税务密码",
                    conten: [
                        "如遗忘密码，可前往所属省份国税网站-点击【忘记密码】-使用法人手机号按提示修改密码",
                    ],
                },
            },
            infoType: "",
        };
    },
    onReady() { },
    async onLoad(options) {
        this.individualForm = {
            enterpriseName: options.companyName,
            creditCode: options.tax,
            age: options.age,
            role: options.role,
            matchType: options.matchType,
            phone: options.phoneNumber,
            provinceId: options?.provinceId
        };
        await this.getProvinceList();
        this.$nextTick(() => {
            this.$refs.individual.setRules(this.indiviRules);
        });
        let province = this.provinceListObj.find(
            (v) => v.id == this.individualForm.provinceId
        );
        this.provinceObj = province;
        this.$set(this.individualForm, "province", province?.name);
    },
    methods: {
        // 开始匹配
        individualConfirmFun() {
            this.$refs.individual.validate().then(async (validate) => {
                if (validate) {
                    if (!this.isChecked) {
                        this.$util.Tips("请阅读并同意授权协议");
                    } else {
                        if (this.needCode) {
                            if (!this.clickCode) {
                                return this.$util.Tips("请先获取验证码");
                            }
                            if (
                                this.individualForm.smsCaptcha &&
                                this.individualForm.smsCaptcha.length < 6
                            ) {
                                return this.$util.Tips("请输入6位验证码");
                            }
                            await this.needCodeFun();
                            return;
                        }

                        if (this.notNeedCode.includes(this.provinceObj.pinyin)) {
                            await this.noteNeedCodeLogin();
                        } else {
                            await this.getBaseData();
                        }
                    }
                }
            });
        },
        //  无需验证省份
        async noteNeedCodeLogin() {
            this.loading = true;
            let obj = {
                provinceName: this.provinceObj.pinyin,
                creditCode: this.individualForm.creditCode.trim(),
                phone: this.individualForm.phone.trim(),
                password: this.individualForm.creditPwd.trim(),
                provinceId: this.provinceObj.id,
                personStand: this.individualForm.role,
                age: this.individualForm.age,
            };
            let res = await onlyAccountApi(obj).finally(() => {
                this.loading = false;
            });
            this.loading = false;
            if (res.code == 200) {
                this.taskId = res.data.id;
                this.enterpriseId = res.data.enterpriseId;
                this.matchFun();
            }
        },

        // 需要验证省份
        async getBaseData() {
            let params = {
                provinceId: this.provinceObj.id,
                provinceName: this.provinceObj.pinyin,
                creditCodeOrTaxPayerId: this.individualForm.creditCode.trim(),
                phoneNumber: this.individualForm.phone.trim(),
                password: this.individualForm.creditPwd.trim(),
                personStand: this.individualForm.role,
                // ageScope: this.individualForm.age,
                age: this.individualForm.age,
            };
            this.loading = true;
            try {
                let res = await taxCompanyLoginApi(params);
                this.loading = false;
                if (res && res.code == 200) {
                    this.uuid = res.data.uuid;
                    this.enterpriseId = res.data.enterpriseId; //企业id
                    this.taskId = res.data.queryTaskId;
                    if (res.data.needSendCaptchaCode == 0) {
                        //不需要验证码
                        await this.matchFun();
                    } else {
                        //需要验证码
                        this.needCode = true;
                    }
                } else {
                    this.$util.Tips(res.data.message);
                }
            } catch (err) {
                this.loading = false;
            }
        },
        // 获取验证码
        getCode() {
            if (this.btnDisabled) return;
            if (this.individualForm.phone) {
                this.btnDisabled = true;
                let params = {
                    phone: this.individualForm.phone,
                    creditCodeOrTaxPayerId: this.individualForm.creditCode,
                    uuid: this.uuid,
                };
                sendSmsCodeApi(params)
                    .then((res) => {
                        this.clickCode = true;
                        this.$util.Tips(res.message);
                    })
                    .catch((err) => {
                        this.$util.Tips(err);
                    })
                    .finally(() => {
                        let timer = setInterval(() => {
                            if (this.countDown > 0) {
                                this.countDown--;
                            } else {
                                clearInterval(timer);
                                this.btnDisabled = false;
                                this.countDown = 60;
                                this.code_QY = "重新发送";
                            }
                        }, 1000);
                    });
            }
        },

        // 需要验证码
        async needCodeFun() {
            let params = {
                provinceName: this.provinceObj.pinyin,
                creditCodeOrTaxPayerId: this.individualForm.creditCode,
                phoneNumber: this.individualForm.phone,
                password: this.individualForm.creditPwd,
                code: this.individualForm.smsCaptcha,
                enterpriseId: this.enterpriseId,
                uuid: this.uuid,
            };
            // 点击获取业务数据 按钮变为数据获取中
            let res = await taxCaptchaApi(params);
            if (res && res.code == 200) {
                this.matchFun();
            } else {
                this.redirectTo({
                     url: `/pagesProduct/matchResult/matchError?enterpriseId=${res.data.enterpriseId}&id=${res.data.id}`,
                });
            }
        },
        // 精准匹配
        async matchFun() {
            // this.loading = true;
            let params = {
                taskId: this.taskId,
                enterpriseId: this.enterpriseId,
                provinceName: this.provinceObj.name,
                creditCode: this.individualForm.creditCode.trim(),
                phone: this.individualForm.phone.trim(),
                creditPwd: this.individualForm.creditPwd.trim(),
                areaId: this.provinceObj.areaId,
                garageStatus: 0,
                enterpriseName: this.individualForm.enterpriseName,
                personStand: this.individualForm.role,
                age: this.individualForm.age,
                channelType: API_CHANNELTYPE.channelType
            };
            try {
                let res = await createMatchEnterpriseApi(params);
                this.loading = false;
                if (res && res.code == 200) {
                    setTimeout(() => {
                        if (res.data.matchStatus == 2) {
                            // 匹配已完成
                            this.redirectTo({
                                url: `/pagesProduct/matchResult/index?enterpriseId=${res.data.enterpriseId}&id=${res.data.id}`,
                            });
                        } else if (res.data.matchStatus == 3) {
                            //匹配失败
                            this.redirectTo({
                                url: `/pagesProduct/matchResult/matchError?enterpriseId=${res.data.enterpriseId}&id=${res.data.id}`,
                            });
                        } else {
                            //匹配中
                            this.isMatching = true
                            // this.$emit("MatchFun");
                        }
                    }, 100);
                }
            } catch (err) {
                this.loading = false;
            }
        },
        showInfo(type) {
            this.infoType = type;
            this.$refs.popupSubmit.open();
        },
        closeDialog() {
            this.$refs.popupSubmit.close();
        },
        preStep() {
            if (this.stepIndex == 0) {
                uni.redirectTo({ url: "/pageHome/company/baseInfo" });
            } else {
                this.stepIndex = this.stepIndex - 1;
            }
        },
        goto(url) {
            uni.switchTab({ url: url });
        },
        async getProvinceList() {
            let res = await getProvince();
            if (res.code === 200) {
                this.provinceListObj = res.data;
                this.provinceList = this.provinceListObj.map((v) => v.name);
            }
        },
        provinceChange(val) {
            this.provinceIndex = val.detail.value;
            this.$set(
                this.individualForm,
                "province",
                this.provinceList[val.detail.value]
            );
            let province = this.provinceListObj.find(
                (v) => v.name == this.individualForm.province
            );
            this.provinceObj = province;
        },
        overDueChange(val) {
            this.overDueIndex = val.detail.value;
            this.$set(
                this.individualForm,
                "overDue",
                this.overDueList[val.detail.value]
            );
        },

        // 税务授权协议
        toAgreement() {
            uni.navigateTo({ url: "/pages/privacy/authorizationAgreement" });
        },
    },
};
</script>

<style lang="scss">
page {
    background-color: #fff !important;
}

.labelStyle {
    display: flex;
    align-items: center;

    .labelText {
        font-weight: 600;
        font-size: 30rpx;
        color: #333333;
        margin-right: 10rpx;
    }

    .label-str {
        color: #dd524d;
        font-weight: bold;
    }

    .img {
        width: 36rpx;
        height: 36rpx;
        margin-right: 10rpx;
    }
}
.formItem {
    /deep/ .uni-forms-item__label {
        margin-left: 50rpx;
    }
    /deep/ .uni-forms-item__content {

        border-bottom: 1px solid #f5f5f5;
    }
}
/deep/ .uni-input-input {
    color: #999;
    font-size: 34rpx;
}
.personFormStyle {

    .footerBox {
        margin-bottom: 63rpx;
        background-color: #fff;
        .checkBox {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            margin-top: 20rpx
        }
        .btnBox,
        .btnBox2 {
            margin-top: 82rpx;
            display: flex;

            .btnTips {
                width: 100%;
                font-weight: 400;
                font-size: 26rpx;
                color: #545454;
                margin-bottom: 40rpx;
                text-align: center;
            }

            .informationBtn {
                margin: 10rpx auto;
                background: #2872fd;
                color: #ffffff;
                font-size: 28rpx;
                font-weight: 500;

                &:first-child {
                    color: #fff;
                    border: 2rpx solid #2872fd;
                    width: 240rpx;
                    // margin-right: 62rpx;
                }

                &:last-child {
                    width: 100%;
                }
            }

            .estimate {
                width: 686rpx;
                height: 88rpx;
                background: #2872fd;
                color: #ffffff;
                font-size: 28rpx;
                font-weight: 500;
            }
        }

        .btnBox2 {
            flex-wrap: wrap;
        }
    }

    .companyName {
        // height: 100rpx;
        padding-right: 10px;
        padding-bottom: 10rpx;
        color: #999999;
        display: flex;
        font-size: 34rpx;
    }
}

/deep/ .uni-forms-item {
    justify-content: space-between;
    border-bottom: 1px solid #f5f5f5;
    margin-top: 10rpx;
    display: block !important;
}

.questionBox {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;

    .form {
        width: 100%;
    }

    .image {
        width: 425rpx;
        margin-top: 25rpx;
        height: 325rpx;
    }

    .des1 {
        padding: 0 110rpx;
        font-weight: 500;
        font-size: 28rpx;
        color: #222222;
        text-align: center;
    }

    .des2 {
        font-weight: 500;
        font-size: 24rpx;
        color: #999999;
        margin-top: 20rpx;
    }
}

.matchBox {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;

    .img {
        margin-top: 80rpx;
        width: 225rpx;
        height: 225rpx;
    }

    .des1 {
        width: 100%;
        text-align: center;
        font-weight: 600;
        font-size: 32rpx;
        color: #191919;
        margin-top: 20rpx;
    }

    .des2 {
        padding: 0 106rpx;
        text-align: center;
    }
}

.flexend {
    margin-top: 0rpx;
    font-size: 28rpx;
}

.info {
    position: absolute;
    right: 20rpx;
}

.uni-padding-wrap {
    width: 550rpx;
    padding: 0 100rpx;
}

/deep/.uni-forms-item__label {
    width: auto !important;
}

/deep/ .uni-input-placeholder {
    font-size: 32rpx !important;
    color: #999;
    font-weight: 500;
}

/deep/ .uni-easyinput {
    text-align: left !important;
}

/deep/.uni-easyinput__content-input {

    // margin-right: 20rpx !important;
    padding-left: 0rpx !important;
    padding-right: 0rpx !important;
}

/deep/ .uni-forms-item__error {
    left: 0 !important;
    // left: auto;
    // right: 0;
}

.btnStyle {
    // width: 160rpx;
    height: 50rpx;
    line-height: 50rpx;
    font-size: 28rpx;
    background: #2872fd;
    border: none;
    color: white;
    border-radius: 30rpx;
}

.btnDisabledStyle {
    // width: 200rpx;
    height: 50rpx;
    line-height: 50rpx;
    font-size: 28rpx;
    background: #cccccc;
    cursor: not-allowed;
    border: none;
    color: white;
}

button:after {
    border: none;
}

.popup-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 15px;
    background-color: #fff;
    text-align: center;
    width: 590rpx;
    margin: 0 auto;
    border-radius: 12rpx;
    position: relative;
    z-index: 999;

    .title {
        margin-top: 30rpx;
        margin-bottom: 30rpx;
        font-weight: bold;
        font-size: 30rpx;
    }

    .content {
        text-align: left;
        line-height: 50rpx;
        padding: 0 30rpx;
    }

    .btn-st {
        width: 93%;
        height: 90rpx;
        line-height: 90rpx;
        border-radius: 45rpx;
        background-color: #3a7eff;
        color: #fff;
        font-weight: bold;
        text-align: center;
        margin-top: 50rpx;
        margin-bottom: 33rpx;
    }
}

/deep/ .uni-checkbox-input {
    border-radius: 50%;
}

.companyTop {
    position: absolute;
    width: 100vw;
    height: 100vh;

    image {
        width: 100%;
        height: 100%;
    }
}

/deep/ .uni-forms-item__label {
    color: #111111;
}

/deep/ .uni-popup__wrapper {
    border-radius: 20rpx;
}
</style>